package com.example.canvasdemo

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.canvasdemo.model.LoginRequest
import com.example.canvasdemo.model.LoginResponse
import com.example.canvasdemo.network.ApiService
import com.example.canvasdemo.network.RetrofitClient
import android.content.Context
import com.example.canvasdemo.model.UserModel
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class LoginActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        val etUsername: EditText = findViewById(R.id.etUsername)
        val etPassword: EditText = findViewById(R.id.etPassword)
        val btnLogin: Button = findViewById(R.id.btnLogin)
        val btnRegister: Button = findViewById(R.id.btnRegister)

        // 点击登录按钮
        btnLogin.setOnClickListener {
            val username = etUsername.text.toString().trim()
            val password = etPassword.text.toString().trim()

            // 检查输入是否为空
            if (username.isEmpty() || password.isEmpty()) {
                showToast("请输入用户名和密码")
                return@setOnClickListener
            }

            // 创建请求对象
            val loginRequest = LoginRequest(username, password)
            loginUser(loginRequest)
        }

        // 跳转到注册界面
        btnRegister.setOnClickListener {
            val intent = Intent(this, RegisterActivity::class.java)
            startActivity(intent)
        }
    }

    private fun loginUser(loginRequest: LoginRequest) {
        val apiService = RetrofitClient.instance.create(ApiService::class.java)

        apiService.loginUser(loginRequest).enqueue(object : Callback<LoginResponse> {
            override fun onResponse(call: Call<LoginResponse>, response: Response<LoginResponse>) {
                if (response.isSuccessful) {
                    val loginResponse = response.body()
                    if (loginResponse != null && loginResponse.status == "success") {
                        val username = loginResponse.username ?: "用户"
                        val userId = loginResponse.userId?.toLong() ?: 0L
                        Log.d("LoginActivity", "Logged in userId: $userId")

                        // 保存用户ID到 SharedPreferences
                        val sharedPref = getSharedPreferences("user_prefs", Context.MODE_PRIVATE)
                        with(sharedPref.edit()) {
                            putLong("userId", userId) // 保持为 Long 类型
                            putString("username", username)
                            apply()
                        }

                        // 获取用户的分数
                        fetchUserScore(userId)

                        // 跳转到主界面
                        showToast("登录成功：欢迎回来，$username！")
                        startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                        finish()
                    } else {
                        showToast("登录失败: ${loginResponse?.message ?: "未知错误"}")
                    }
                } else {
                    showToast("登录失败: ${response.message()}")
                }
            }

            override fun onFailure(call: Call<LoginResponse>, t: Throwable) {
                showToast("网络错误: ${t.message}")
                Log.e("LoginActivity", "网络错误", t)
            }
        })
    }

    private fun fetchUserScore(userId: Long) {
        val apiService = RetrofitClient.instance.create(ApiService::class.java)
        apiService.getUserById(userId).enqueue(object : Callback<UserModel> {
            override fun onResponse(call: Call<UserModel>, response: Response<UserModel>) {
                if (response.isSuccessful) {
                    val user = response.body()
                    if (user != null) {
                        val score = user.score // 假设 UserModel 中有 score 字段
                        Log.d("LoginActivity", "User score: $score")
                    } else {
                        Log.e("LoginActivity", "Failed to get user data")
                    }
                } else {
                    Log.e("LoginActivity", "Failed to fetch user data: ${response.message()}")
                }
            }

            override fun onFailure(call: Call<UserModel>, t: Throwable) {
                Log.e("LoginActivity", "Network error: ${t.message}")
            }
        })
    }
    // 统一 Toast 方法
    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
}


